package com.iceflame.zxingane.funs;

import java.util.HashMap;
import java.util.Map;

import com.adobe.fre.FREArray;
import com.adobe.fre.FREContext;
import com.adobe.fre.FREFunction;
import com.adobe.fre.FREObject;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.iceflame.zxingane.EventType;
import com.iceflame.zxingane.ZXingAne;

public class Encode implements FREFunction {

	@Override
	public FREObject call(FREContext arg0, FREObject[] arg1) {
		if(arg1.length == 0){
			return null;
		}
		long time = System.currentTimeMillis();
		ZXingAne.dispatchEvent(EventType.DEBUG, "StartEncode");
        try {  
        	int encodew = arg1[0].getAsInt();
        	int encodeh = arg1[1].getAsInt();
        	String contents = arg1[2].getAsString();
        	Map<EncodeHintType, String> hints = new HashMap<EncodeHintType, String>();
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); 
            BitMatrix matrix = null;  
            matrix = new MultiFormatWriter().
            		encode(contents,BarcodeFormat.QR_CODE, encodew, encodeh, hints); 
    	    int width = matrix.getWidth();
    	    int height = matrix.getHeight();
    	    ZXingAne.dispatchEvent(EventType.DEBUG, "EncodeSize" + width + "*" + height);
    	    FREArray array = FREArray.newArray((width * height) + 2);
    	    array.setObjectAt(0, FREObject.newObject(width));
    	    array.setObjectAt(1, FREObject.newObject(height));
    	    for (int y = 0; y < height; y++) {
  		    	int offset = y * width;
  		    	for (int x = 0; x < width; x++) {
  		    		int index = offset + x + 2;
  		    		array.setObjectAt(index, FREObject.newObject(matrix.get(x, y)));
  		    	}
    	    }
    	    long timeUse = System.currentTimeMillis() - time;
    		ZXingAne.dispatchEvent(EventType.DEBUG, "EncodeComplete,Use:" + timeUse);
    	    return array;
        } catch (Exception e) {  
            String errStr = e.getMessage();
            ZXingAne.dispatchEvent(EventType.ERROR, "EncodeCatchError:" + errStr);
        }
        return null;
	}
}
